package xin.marcher.wind.process.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import xin.marcher.wind.process.converter.ProcessConverter;
import xin.marcher.wind.process.dao.ProcessNodeDAO;
import xin.marcher.wind.process.domain.dto.ProcessNodeDTO;
import xin.marcher.wind.process.domain.dto.ProcessNodeListDTO;
import xin.marcher.wind.process.domain.entity.ProcessNodeDO;
import xin.marcher.wind.process.domain.request.ProcessNodeQuery;
import xin.marcher.wind.process.domain.request.SaveProcessNodeRequest;
import xin.marcher.wind.process.service.ProcessNodeService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * 
 * @version 1.0
 */
@Slf4j
@Service
public class ProcessNodeServiceImpl implements ProcessNodeService {

    @Resource
    private ProcessNodeDAO processNodeDAO;

    @Resource
    private ProcessConverter processNodeConverter;

    @Override
    public void save(SaveProcessNodeRequest request) {

        // 1、根据节点名称查询对应的流程节点
        ProcessNodeDO processNode = processNodeDAO.getOne(request.getName());
        if(null == processNode) {
            // 新增
            processNode = new ProcessNodeDO();
        }

        // 2、设置属性
        processNode.setType(request.getType());
        processNode.setName(request.getName());
        processNode.setBeanName(request.getBeanName());
        processNode.setBeanClazzName(request.getBeanClazzName());
        processNode.setRemark(request.getRemark());

        // 3、保存
        processNodeDAO.saveOrUpdate(processNode);
    }

    @Override
    public void delete(String name) {

        // 1、根据节点名称查询对应的流程节点
        ProcessNodeDO processNode = processNodeDAO.getOne(name);
        if(null == processNode) {
           return;
        }

        // 2、移除
        processNodeDAO.deleteByName(name);
    }

    @Override
    public ProcessNodeDTO detail(String name) {
        // 1、根据节点名称查询对应的流程节点
        ProcessNodeDO processNode = processNodeDAO.getOne(name);
        if(null == processNode) {
            return null;
        }
        // 2、转化
        return processNodeConverter.convertToProcessNodeDTO(processNode);
    }

    @Override
    public List<ProcessNodeListDTO> list(ProcessNodeQuery query) {
        // 1、根据条件查询流程节点
        List<ProcessNodeDO> list = processNodeDAO.listBy(query);
        if(CollectionUtils.isEmpty(list)) {
            return null;
        }

        // 2、组装查询条件
        List<ProcessNodeListDTO> result = new ArrayList<>();
        list.forEach(processNodeDO -> {
            result.add(new ProcessNodeListDTO(processNodeDO.getId(), processNodeDO.getType(), processNodeDO.getName()));
        });
        return result;
    }
}
